package com.haizhi.crm.tag.manager.impl;

import com.alibaba.fastjson.JSON;
import com.haizhi.crm.common.constant.TagStatus;
import com.haizhi.crm.common.exception.UnexpectedStatusException;
import com.haizhi.crm.common.rest.RestService;
import com.haizhi.crm.tag.manager.TagManager;
import com.haizhi.crm.tag.model.TagPagReq;
import com.haizhi.crm.tag.model.TagPageResp;
import com.haizhi.crm.tag.model.TagReq;
import com.haizhi.crm.tag.model.TagResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by chengmo on 2018/5/16.
 */
@Service
public class TagManagerImpl implements TagManager {

    private static final String PATH_TAG = "/tag";
    private static final String PATH_FIND_BY_OBJECT_KEYS = PATH_TAG + "/findByObjectKeys";
    private static final String PATH_QUERY_PAGE = PATH_TAG + "/findPage";
    private static final String PATH_GET_ONE = PATH_TAG + "/get";
    private static final String PATH_SAVE = PATH_TAG + "/save";
    private static final String PATH_UPDATE = PATH_TAG + "/update";
    private static final String PATH_DELETE = PATH_TAG + "/delete";

    @Value("${tag.manager.url.graph-tag-analytics:}" )
    private String restUrl;
    @Autowired
    private RestService restService;

    @Override
    public TagResp findByObjectKeys(TagReq request) {
        return this.doPost(PATH_FIND_BY_OBJECT_KEYS, request);
    }

    @Override
    public TagPageResp findPage(TagPagReq request) {
        return this.doPost(PATH_QUERY_PAGE, request, TagPageResp.class);
    }

    @Override
    public TagResp get(TagReq request) {
        return this.doPost(PATH_GET_ONE, request);
    }

    @Override
    public TagResp save(TagReq request) {
        return this.doPost(PATH_SAVE, request);
    }

    @Override
    public TagResp update(TagReq request) {
        return this.doPost(PATH_UPDATE, request);
    }

    @Override
    public TagResp delete(TagReq request) {
        return this.doPost(PATH_DELETE, request);
    }

    ///////////////////////
    // private functions
    ///////////////////////
    private TagResp doPost(String path, TagReq request) {
        return this.doPost(path, request, TagResp.class);
    }

    private <Req, Resp> Resp doPost(String path, Req request, Class<Resp> cls) {
        try {
            return restService.doPost(restUrl + path, request, cls);
        } catch (Exception e) {
            throw new UnexpectedStatusException(TagStatus.CALL_REST_ERROR, e,
                    JSON.toJSONString(request));
        }
    }
}
